<?php

namespace app\api\controller;
use think\Controller;
use data\Json;
use think\Request;
use app\common\model\Activity;
use app\common\model\ActivityCalendar;
/**
 * 供应商api接口
 *
 * @icon fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类
 */
class Supplier extends Base
{

    protected $model = null;
    protected $supplier_model = null;
    protected $token = null;
    protected $supplier = null;

    public function _initialize()
    {
         $this->token = request()->header('token');
         $this->supplier_model = model('Supplier');
        // $this->supplier = $this->supplier_model->getUserInfo($this->token);
         $this->supplier = $this->supplier_model->get('1');
    }

    public function info(Request $request)
    {
		if(!$this->supplier)return Json::json_send(1);

    	if($request->isPost())
        {
        	$data = input();
            if(request()->file('avatar'))
            {
                $data['avatar'] = $this->upload(request()->file('avatar'));
            }
            $result = $this->supplier_model->isUpdate(true)->allowField(true)->save($data,['id'=>$this->supplier['id']]);
            if( $result === false)
            {
                return Json::json_send(7);
            }
        }

        $data = [];
        $supplier = $this->supplier_model->where('id',$this->supplier['id'])->find();
        $data['type'] = $supplier['type'];
        $data['avatar'] = $supplier['avatar'];
        $data['name'] = $supplier['name'];
        $data['mobile'] = $supplier['mobile'];
        $data['city'] = $supplier['city'];
        if($this->supplier['type'] < 3)
        {
        	$data['person'] = $supplier['person'];
        	$data['address'] = $supplier['address'];
            $data['sitetype'] = $supplier['sitetype'];
        }

        if($this->supplier['type'] == 2)
        {
        	$data['company_post'] = $supplier['company_post'];
        	//$data['is_ticket'] = $supplier['is_ticket']==1?"是":"否";
            $data['is_ticket'] = $supplier['is_ticket'];
        }

        if($this->supplier['type'] == 3)
        {
        	$data['company_post'] = $supplier['company_post'];
        	$data['truename'] = $supplier['truename'];
        	$data['office'] = $supplier['office'];
        	$data['honor'] = $supplier['honor'];
        	$data['selfdesc'] = $supplier['selfdesc'];
        }
        return Json::json_send(0,'',$data);
    }

     // 极光推送消息列表
    public function messages()
    {
        if(!$this->supplier)return Json::json_send(1);
        $list = model('JpushData')->field('msg,createtime')->where(['type'=>1,'alias'=>$this->supplier['mobile']])->select();
        return Json::json_send(0,'',$list);
    }

    // 充值
    public function recharge()
    {
        if(!$this->supplier)return Json::json_send(1);
        $param = [
            'good_id'   => $this->supplier['id'],
            'total_fee' => input('fee',0),
            'title'     => '充值',
            'channel'   => input('channel','ALI_APP'),//"ALI_APP";
            'type'      => 7,//"充值";
        ];
        $this->redirect(url('pay/index', $param));
    }

     // 提现
    public function withdrawals()
    {
        if(!$this->supplier)return Json::json_send(1);
        $param = [
            'good_id'   => $this->supplier['id'],
            'total_fee' => input('fee',0),
            'title'     => '提现',
            'channel'   => input('channel','ALI_APP'),//"ALI_APP";
            'type'      => 8,//"提现";
        ];
        // 生成转账订单
        $order_id = action('pay/prepay',$param);
        // 申请转账
        $this->redirect(url('pay/transfer', ['order_id'=>$order_id]));
    }

    // 收入
    public function income()
    {
        if(!$this->supplier)
        {
            return Json::json_send(1);
        }
 
        $data['income'] = $this->supplier['sum_income'];
        $data['wallet'] = $this->supplier['wallet_money'];

        // 明细
        //$details = collection(model('TravelDistribution')->field('title,content,mode,fee,createtime')->where(['type'=>1,'user_id'=>$this->supplier['id']])->select())->toArray();
        $details = collection(model('Paylog')->field('title,content,mode,fee,createtime')->where(['type'=>1,'user_id'=>$this->supplier['id']])->select())->toArray();
        $data['details'] = $details;
        return Json::json_send(0,'',$data);
    }

    // 主页日历
    public function calendar(Request $request)
    {
    	if(!$this->supplier)return Json::json_send(1);

        if(input('activity_id'))
        {
            $activity_id = input('activity_id');

            if($request->isPost())
            {
                $data = input();
                $vali = $this->validate($data,'ActivityCalendar');
                if($vali !== true){
                    return Json::json_send($vali);
                }
                $selected = $data['selected'];
                $data['activity_id'] = $activity_id;
                if(!strpos($selected,','))
                {
                    $data['time'] = $selected;
                    if(model('ActivityCalendar')->data($data)->allowField(true)->save())
                    {
                        return Json::json_send(0);
                    }
                }

                foreach (explode(',', $selected) as $key => $value) {
                    $data['time'] = $value;
                    model('ActivityCalendar')->data($data)->isUpdate(false)->allowField(true)->save();
                }
                return Json::json_send(0);
            }

            if(input('time'))
            {
                $time = input('time');
                if(input('is_delete'))
                {
                    if(ActivityCalendar::where('activity_id',$activity_id)->where('time',input('time'))->update(['is_delete'=>1]))
                    {
                        return Json::json_send(0);
                    }
                    return Json::json_send(9);
                }

                $data = ActivityCalendar::field('remark,remind,time')->where(['activity_id'=>$activity_id,'time'=>$time,'is_delete'=>0])->find();
                return Json::json_send(0,'',$data);
            }

            $data = [];
           // $data['activity_id'] = $activity_id;
            $selected = ActivityCalendar::where('activity_id',$activity_id)->where('is_delete',0)->select();
            foreach ($selected as $key => $value) 
            {
                $year = date('Y',$value['time']);
                $data[$year]  =  [];
            }
            foreach ($selected as $key => $value) {
                $year = date('Y',$value['time']);
                $month = date('m',$value['time']);
                $data[$year][$month] = [];
                $data[$year][$month]['lastday'] = date('t',$value['time']);
            }
            foreach ($selected as $key => $value) {
                $year = date('Y',$value['time']);
                $month = date('m',$value['time']);
                $data[$year][$month]['date'] = [];
             
            }
            foreach ($selected as $key => $value) {
                $year = date('Y',$value['time']);
                $month = date('m',$value['time']);
                $lastday = date('t',$value['time']);
                $data[$year][$month]['lastday']--;
                array_push($data[$year][$month]['date'],$value['time']);
            }

            $return = [];
            foreach ($data as $k => $v) {
                $months = [];
                foreach ($v as $ck => $cv) {
                    $month = [
                        'month'=>$ck,
                        'lastday'=>$cv['lastday'],
                        'date' =>$cv['date']
                    ];
                    array_push($months, $month);
                }
                $year = [
                    'year' => $k,
                    'months' => $months
                ];
                array_push($return, $year);
            }

            return Json::json_send(0,'',$return);
        }

        $activityList = Activity::field('id,name')->where(['supplier_id'=>$this->supplier['id'],'is_delete'=>0])->select();
        return Json::json_send(0,'',$activityList);
    }

    public function activities(Request $request)
    {
    	if($request->isPost())
        {
            if(!$this->supplier)return Json::json_send(1);
        	$data = input();
        	if(!request()->file('poster'))
        	{
        		return Json::json_send(30019);
        	}
        	$data['poster'] = $this->upload(request()->file('poster'));
        	$data['supplier_id'] = $this->supplier['id'];
        	switch ($this->supplier['type']) {
        		case '1':
                    $data['is_site'] = 1;
        			$scenes = "Activity.site";
        			break;
        		case '2':
        			$scenes = "Activity.activity";
        			break;
        		default:
        			$scenes = "Activity.master";
        			break;
        	}
			$vali = $this->validate($data,$scenes);
	        if($vali !== true){
	            return Json::json_send($vali);
	        }

            if(input('address'))
            {
                $baidu = build_sn(input('address'));
                $data['longitude'] = $baidu['lng'];
                $data['latitude']  = $baidu['lat'];
            }

            if(input('site_address'))
            {
                $baidu = build_sn(input('site_address'));
                $data['longitude'] = $baidu['lng'];
                $data['latitude']  = $baidu['lat'];
            }

	        if(input('activityid'))
	        {
	        	$result = model('Activity')->isUpdate(true)->allowField(true)->save($data,['id'=>input('activityid')]);
	        }
	        else
	        {
	        	$result = model('Activity')->allowField(true)->save($data);
	        }
	         
	        if($result !== false)
			{
				return Json::json_send(0,'提交成功');
			}
			return Json::json_send(7);
	    }

	    if(input('activityid'))
	    {
            $activity_id = input('activityid',0);
	    	if(input('is_delete'))
	    	{
	    		if(model('Activity')->where('id',$activity_id)->update(['is_delete'=>1]))
	    		{
	    			return Json::json_send(0,'删除成功');
	    		}
	    		return Json::json_send(8);
	    	}
	    	//$activity= model('Activity')->where('id',$activity_id)->find();
            $activity= model('Activity')->get($activity_id);
            $supplier= model('Supplier')->get($activity['supplier_id']);
	    	if(!$activity){
	    		return Json::json_send(4);
	    	}

            if(input('flag'))
            {
                $flag = input('flag');
                switch ($flag) {
                    case '1':
                        return Json::json_send(0,'',$activity);
                        break;
                    case '2':
                        $return['poster'] = $activity['poster'];
                        $return['url'] = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
                        // $url = config('url_domain_root').url('supplier/activities',['activityid'=>$activity_id]);
                        return Json::json_send(0,'',$return);
                        break;
                    default:
                        break;
                }
            }   

            $activity['site'] = $activity['is_site'] == 1?"包场地":"不包场地";
            $city = model('city')->get($activity['city_id']);
            $activity['city'] = $city['name'];

            $ac_model = model('ActivityCalendar');
            $selected_time = [];
            $video_timeds = $ac_model->where('activity_id',$activity_id)->select();

            foreach ($video_timeds as $key => $value) 
            {
                $vtime = date('Y-m-d',$value['time']);
                array_push($selected_time,$vtime);
            }

            $activity['selected_time'] = json_encode($selected_time);

            if($activity['plan'])
            {
                $activity['plan'] = json_decode($activity['plan'],true);
            }

            if($activity['desc'])
            {
                $arr = json_decode($activity['desc'],true);
                $text = $arr['text'];
                $length = 0;
                foreach ($arr['img'] as $k => $v)
                {
                    $img = '<img src="'.stripslashes($v['body']).'" class="img marginT15" />';
                    $text = afterStr($text,$v['position']+$length,$img);
                    $length += strlen($img);
                }
                $activity['desc']  = $text;
            }

            $activity['begintime'] = Activity::getBeginTime($activity['begintime']);
            $activity['endtime']   = Activity::getEndTime($activity['endtime']);
            $activity['is_metro'] = empty($activity['is_metro'])?"否":"是";
            $activity['park_number'] = Activity::getParkNumber($activity['park_number']);
            $activity['is_ticket'] = empty($activity['is_ticket'])?"不可开票":"可开票";
            $activity['extra_service']=explode(',', Activity::getExtraService($activity['extra_service']));
            //return ['status'=>0,'data' => json_encode($selected_time)];
            // 1=场地商,2=活动方,3=主讲老师
            switch ($supplier['type']) {
                case '1':
                    $activity['desc_title'] = '场地概述';
                    $activity['type'] = '1';
                    $this->view->assign('activity',$activity);
                    return $this->view->fetch('activity/siteinfo');// 活动商
                    break;
                case '2':
                    $activity['desc_title'] = '活动描述';
                    $activity['type'] = '2';
                    break;
                default:
                    $activity['desc_title'] = '课程描述';
                    $activity['type'] = '3';
                    break;
            }

            $this->view->assign('activity',$activity);
	    	return $this->view->fetch('activity/info');// 活动商
	    }

	    $data = [];
	    $activities = model('Activity')->where('supplier_id',$this->supplier['id'])->where('is_delete',0)->order('id desc')->select();
	    foreach ($activities as $key => $value) {
            $data[$key]['id'] =  $value['id'];
	    	$data[$key]['poster'] =  $value['poster'];
	    	$data[$key]['createtime'] =  date("Y-m-d",$value['createtime']);
	    	$data[$key]['name'] =  $value['name'];
	    	$data[$key]['fee'] =  $value['fee'];
	    	if($this->supplier['type'] == 1)
	    	{
	    		$data[$key]['address'] =  $value['address'];
	    	}
	    	else
	    	{
	    		$data[$key]['time'] =  $value['time'];
    			$data[$key]['is_site'] =  $value['is_site']==1?"包场地":"不包场地";
    			$activity_cat = model('Activity_cat')->where('id',$value['category'])->find();
    			$category = $activity_cat['name'];
	    		$data[$key]['category'] =  $category;
                if($this->supplier['type'] == 3){
                    $course_cat = model('CourseCat')->where('id',$value['category'])->find();
                    $classes = $course_cat['name'];
                    $data[$key]['classes'] =  $classes;
                }
	    	}
	    }
    	return Json::json_send(0,'',$data);
    }


    public function cities()
    {
        $type = input('type',0);
    	if(!$this->supplier)
    	{
    		return Json::json_send(1);
    	}
    	$data = model('city')->where('type',$type)->select();
    	return Json::json_send(0,'',$data);
    }

    public function businessTime()
    {
        if(!$this->supplier)return Json::json_send(1);
        $data = model('BusinessTime')->all();
        return Json::json_send(0,'',$data);
    }
}
